package com.cmcc.aregister.ui.activity;

import java.util.Calendar;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtil;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.MemberModel;
import com.cmcc.aregister.cs.util.IdCardHelper;

public class MemberEditorActivity extends ParentActivity implements
    OnDateSetListener {
    private final String TAG = "PersonInfoEditor";
    private Button homeBtn, finishBtn;
    private EditText nameET, phoneNum, idCard, ssCard;
    private TextView birthT;

    private TextView tv_register_certificate_type, tv_register_family_type;
    private int cardIndex, relationIndex;

    private ImageView iv_register_man, iv_register_woman;
    private PopupWindow popupWindow;

    private int mYear;
    private int mMonth;
    private int mDay;
    int sex;
    boolean isChanged = false;
    String resultMsg;
    String name, mobile, birth, card, scard, card_type;
    private int relation;
    private DatabaseAdapter mDatabaseAdapter;
    String url;
    private String result;
    static final int DATE_DIALOG_ID = 1;
    private int[] relationId = null;
    private String[] relationText = null;
    private static final String[] cardTypeValue = new String[] { "01", "02",
        "03", "04" };
    private static final String[] cardTypeText = new String[] { "身份证",
        "港澳台居民身份证", "护照", "军官证" };
    private MemberModel member;
    private int flag = 0;// 操作类型
    private String f_id; // 家庭档案ID
    private String area_id;
    private String city_id;

    private Object[] objs = new Object[4];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        objs = ConfigUtilHelper.getRelation(this);
        init(R.layout.p_member_editor);
        mHttpManager.setCxt(getParent());
    }

    @Override
    protected void setupData() {
        flag = getIntent().getIntExtra(Arguments.MEMBER_OPER_FLAG, 0);
        if (flag == ConfigUtil.MEMBER_OPER_FLAG_UPD) {
            member = (MemberModel) getIntent().getSerializableExtra(
                Arguments.MEMBER_MODEL);
        }
        if (flag == ConfigUtil.MEMBER_OPER_FLAG_ADD) {
            f_id = getIntent().getStringExtra(Arguments.FAMILY_ID);
            area_id = getIntent().getStringExtra(Arguments.AREA_ID);
            city_id = getIntent().getStringExtra(Arguments.CITY_ID);
        }

    }

    @Override
    protected void setupView() {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.family_add_title);
        mDatabaseAdapter = new DatabaseAdapter(this);
        homeBtn = (Button) findViewById(R.id.top_left_image);
        homeBtn.setVisibility(View.VISIBLE);
        homeBtn.setOnClickListener(onClickListener);
        finishBtn = (Button) findViewById(R.id.top_right_btn);
        finishBtn.setVisibility(View.VISIBLE);
        finishBtn.setText(getString(R.string.finish));
        finishBtn.setTextSize(18);
        finishBtn.setTextColor(getResources().getColor(R.color.blue));
        finishBtn.setBackgroundDrawable(null);
        finishBtn.setOnClickListener(onClickListener);

        nameET = (EditText) findViewById(R.id.name);
        phoneNum = (EditText) findViewById(R.id.phone_num);
        // phoneNum.setEnabled(false);//手机号码不能更改
        idCard = (EditText) findViewById(R.id.id_card);
        ssCard = (EditText) findViewById(R.id.ss_card);

        birthT = (TextView) findViewById(R.id.birth);
        birthT.setOnClickListener(onClickListener);
        // birthLayout = (LinearLayout) findViewById(R.id.birth_layout);
        //
        // birthLayout.setOnClickListener(onClickListener);

        iv_register_man = (ImageView) findViewById(R.id.iv_register_man);
        iv_register_man.setOnClickListener(onClickListener);
        iv_register_woman = (ImageView) findViewById(R.id.iv_register_woman);
        iv_register_woman.setOnClickListener(onClickListener);

        // relationSpinner = (Spinner) findViewById(R.id.spinner_relation);
        tv_register_family_type = (TextView) findViewById(R.id.tv_register_family_type);
        findViewById(R.id.spinner_familytype).setOnClickListener(
            onClickListener);

        // cardTypeSpinner = (Spinner) findViewById(R.id.spinner_cardtype);
        tv_register_certificate_type = (TextView) findViewById(R.id.tv_register_certificate_type);
        findViewById(R.id.spinner_cardtype).setOnClickListener(onClickListener);
        initDate();
        // initCardType();
        if (flag == ConfigUtil.MEMBER_OPER_FLAG_UPD) {
            nameET.setEnabled(false); // 姓名不能修改
            // ((TextView) findViewById(R.id.title)).setText("编辑家庭成员");
            relationText = context.getResources().getStringArray(
                R.array.member_relation);
            relationId = context.getResources().getIntArray(
                R.array.member_relation_value);
            // initRelation();
            setUpdateData();
        }
        else if (flag == ConfigUtil.MEMBER_OPER_FLAG_ADD) {
            // ((ImageView) findViewById(R.id.title)).setBackgroundResource(r.);
            // changeRelationValue(radioMan.isChecked());
            changeRelationValue(true);
        }
    }

    private void changeRelationValue(boolean isMan) {
        if (flag == ConfigUtil.MEMBER_OPER_FLAG_ADD) {
            if (isMan) {
                relationId = (int[]) objs[1];
                relationText = (String[]) objs[0];
            }
            else {
                relationId = (int[]) objs[3];
                relationText = (String[]) objs[2];
            }
            // initRelation();
        }
    }

    private void setUpdateData() {
        if (member != null) {
            nameET.setText(member.truename);
            phoneNum.setText(member.phone);
            idCard.setText(member.card);
            ssCard.setText(member.social_card);
            birthT.setText(member.birth);
            if (member.sex == 0) {
                // radioMan.setChecked(true);
                iv_register_man.setImageResource(R.drawable.register_man_on);
                iv_register_woman
                    .setImageResource(R.drawable.register_woman_off);
            }
            else if (member.sex == 1) {
                // radioWoman.setChecked(true);
                iv_register_man.setImageResource(R.drawable.register_man_off);
                iv_register_woman
                    .setImageResource(R.drawable.register_woman_on);
            }
            int position = ConfigUtilHelper.getRelationPosition(this,
                member.relation, member.sex);
            if (position >= 0) {
                // relationSpinner.setSelection(position);
                tv_register_family_type.setText(relationText[position]);
            }
            else {

            }
            int cardtypepostion = getCardTypePosition(member.card_type);
            if (cardtypepostion >= 0) {
                // cardTypeSpinner.setSelection(cardtypepostion);
                tv_register_certificate_type
                    .setText(cardTypeText[cardtypepostion]);
            }
        }
    }

    private int getCardTypePosition(String cardtype) {
        int position = -1;
        for (int i = 0; i < cardTypeValue.length; i++) {
            if (cardTypeValue[i].equalsIgnoreCase(cardtype)) {
                position = i;
                break;
            }
        }
        return position;
    }

    private int getRelationPosition(int relation) {
        int position = -1;
        for (int i = 0; i < relationId.length; i++) {
            if (relation == relationId[i]) {
                position = i;
                break;
            }
        }
        return position;
    }

    // private void initRelation() {
    // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    // android.R.layout.simple_spinner_item, relationText);
    // adapter
    // .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // relationSpinner.setAdapter(adapter);
    // relationSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    //
    // @Override
    // public void onItemSelected(AdapterView<?> arg0, View arg1,
    // int arg2, long arg3) {
    // TextView tView = (TextView) arg1;
    // tView.setTextColor(Color.BLACK);
    // }
    //
    // @Override
    // public void onNothingSelected(AdapterView<?> arg0) {
    //
    // }
    //
    // });
    // }

    private boolean checkValid() {
        name = nameET.getText().toString().trim();
        name = name.replaceAll("\\s*", "");
        mobile = phoneNum.getText().toString().trim();
        mobile = mobile.replaceAll("\\s*", "");
        birth = birthT.getText().toString().trim();
        birth = birth.replaceAll("\\s*", "");
        card = idCard.getText().toString().trim();
        card = card.replaceAll("\\s*", "");
        scard = ssCard.getText().toString().trim();
        scard = scard.replaceAll("\\s*", "");

        // int selection = relationSpinner.getSelectedItemPosition();
        // relation = relationId[selection];
        relation = relationId[relationIndex];

        // int cardtypeselection = cardTypeSpinner.getSelectedItemPosition();
        // card_type = cardTypeValue[cardtypeselection];
        card_type = cardTypeValue[cardIndex];

        return isCheck(name, mobile, birth, card_type, card, scard);
    }

    @Override
    public void doSomeWork() {
        finish();
    }

    private void editMember() {
        if (checkValid()) {
            showProgressDialogNew(R.string.progressing_tips);
            String params = "cid=8&token=wxcityMobileClient&mid="
                + member.member_id + "&linkman=" + name + "&phone=" + mobile
                + "&card=" + card + "&card_type=" + card_type + "&sex=" + sex
                + "&birth=" + birth + "&social_card=" + scard + "&relation="
                + relation;
            editMemberTask = new HttpAsyncTask(HttpAsyncTask.POST,
                GlobalSetting.XML_UPD_MEMBER, Arguments.UPD_MEMBER_URL, params,
                HttpAsyncTask.CACHE_TYPE_ACTION, true);
            editMemberTask.setUIHandler(editMemberTastHandler);
            mHttpManager.execute(editMemberTask);
        }
    }

    private HttpAsyncTask editMemberTask;
    private Handler editMemberTastHandler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String status = (String) httpMap.get(Arguments.XML_STATUS);
                    String message = (String) httpMap
                        .get(Arguments.XML_MESSAGE);
                    if (Integer.parseInt(status) > 0) {
                        _showInfoDialog(message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {

                                }
                            });
                    }
                    else {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.edit_member_error),
                    getString(R.string.close));
                break;
            }
        }
    };

    private void addMember() {
        if (checkValid()) {
            showProgressDialogNew(R.string.progressing_tips);
            String params = "cid=8&token=wxcityMobileClient&f_id=" + f_id
                + "&truename=" + name + "&phone=" + mobile + "&card=" + card
                + "&card_type=" + card_type + "&sex=" + sex + "&birth=" + birth
                + "&social_card=" + scard + "&relation=" + relation
                + "&ared_id=" + area_id + "&city_id=" + city_id;
            addMemberTask = new HttpAsyncTask(HttpAsyncTask.POST,
                GlobalSetting.XML_ADD_MEMBER, Arguments.ADD_MEMBER_URL, params,
                HttpAsyncTask.CACHE_TYPE_ACTION, true);
            addMemberTask.setUIHandler(addMemberTastHandler);
            mHttpManager.execute(addMemberTask);
        }
    }

    private HttpAsyncTask addMemberTask;
    private Handler addMemberTastHandler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String status = (String) httpMap.get(Arguments.XML_STATUS);
                    String message = (String) httpMap
                        .get(Arguments.XML_MESSAGE);
                    if (Integer.parseInt(status) > 0) {
                        _showInfoDialog(message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {

                                }
                            });
                    }
                    else {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                }
                else {
                    showMsg(R.string.add_member_error);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.add_member_error),
                    getString(R.string.close));
                break;
            }
        }
    };

    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
            case R.id.top_left_image:
                gobackHome();
                break;
            case R.id.top_right_btn:
                if (flag == ConfigUtil.MEMBER_OPER_FLAG_ADD) {
                    addMember();
                }
                if (flag == ConfigUtil.MEMBER_OPER_FLAG_UPD) {
                    editMember();
                }
                break;
            case R.id.birth:
                // String card_type = cardTypeValue[cardTypeSpinner
                // .getSelectedItemPosition()];
                String card_type = cardTypeValue[cardIndex];
                String idCardStr = idCard.getText().toString().trim();
                if ("01".equals(card_type)
                    && ConfigUtilHelper.isNotEmpty(idCardStr)) {
                    boolean flag = IdCardHelper.validateCard(idCardStr);
                    if (!flag) {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.idcard_error),
                            getString(R.string.dialog_yes));
                        return;
                    }

                    mYear = IdCardHelper.getYearByIdCard(idCardStr);
                    mMonth = IdCardHelper.getMonthByIdCard(idCardStr);
                    mDay = IdCardHelper.getDateByIdCard(idCardStr);
                    updateDisplay_();
                }
                else {
                    String birth = birthT.getText().toString();
                    if (ConfigUtilHelper.isNotEmpty(birth)) {
                        String[] arr = birth.split("-");
                        mYear = Integer.parseInt(arr[0]);
                        mMonth = Integer.parseInt(arr[1]) - 1;
                        mDay = Integer.parseInt(arr[2]);
                    }
                    showDateSetDialog();
                }
                break;
            case R.id.cancel_btn:
                closeDlg();
                break;
            case R.id.spinner_cardtype:
                new AlertDialog.Builder(MemberEditorActivity.this).setItems(
                    cardTypeText, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            tv_register_certificate_type
                                .setText(cardTypeText[arg1]);
                            cardIndex = arg1;
                        }
                    }).show();
                break;
            case R.id.spinner_familytype:
                new AlertDialog.Builder(MemberEditorActivity.this).setItems(
                    relationText, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            tv_register_family_type.setText(relationText[arg1]);
                            relationIndex = arg1;
                        }
                    }).show();
                break;
            case R.id.iv_register_man:
                sex = 0;
                changeRelationValue(true);
                iv_register_man.setImageResource(R.drawable.register_man_on);
                iv_register_woman
                    .setImageResource(R.drawable.register_woman_off);
                break;
            case R.id.iv_register_woman:
                sex = 1;
                changeRelationValue(false);
                iv_register_man.setImageResource(R.drawable.register_man_off);
                iv_register_woman
                    .setImageResource(R.drawable.register_woman_on);
                break;
            default:
                break;
            }
        }

    };

    private void closeDlg() {
        if (popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    private boolean isCheck(String name, String mobile, String birth,
        String card_type, String card, String scard) {
        if (!ConfigUtilHelper.isNotEmpty(name)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.name_is_null),
                getString(R.string.dialog_yes));
            return false;
        }
        else if (ConfigUtilHelper.isNotEmpty(mobile)
            && !ConfigUtilHelper.isMobileNum11(mobile)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_err), getString(R.string.dialog_yes));
            return false;
        }
        else if ("01".equals(card_type) && ConfigUtilHelper.isNotEmpty(card)) {
            if (!IdCardHelper.validateCard(card)) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.idcard_error),
                    getString(R.string.dialog_yes));
                return false;
            }
            else if (("M".equals(IdCardHelper.getGenderByIdCard(card)) && sex != 0)
                || ("F".equals(IdCardHelper.getGenderByIdCard(card)) && sex != 1)) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.card_sex_err),
                    getString(R.string.dialog_yes));
                return false;
            }
            else {
                mYear = IdCardHelper.getYearByIdCard(card);
                mMonth = IdCardHelper.getMonthByIdCard(card);
                mDay = IdCardHelper.getDateByIdCard(card);
                updateDisplay_();
            }
        }
        else if (!scard.equals("") && scard.length() != 10) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.social_card_err),
                getString(R.string.dialog_yes));
            return false;
        }
        else if (!ConfigUtilHelper.isNotEmpty(birthT.getText().toString())) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.birth_null), getString(R.string.dialog_yes));
            return false;
        }
        return true;
    }

    private void showDateSetDialog() {
        new DatePickerDialog(context, this, mYear, mMonth, mDay).show();
    }

    // 回到主界面
    private void gobackHome() {
        Intent intent = new Intent(MemberEditorActivity.this,
            NewIndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, this, mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DATE_DIALOG_ID:
            ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
            break;
        }
    }

    private void initDate() {
        final Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @SuppressWarnings("unused")
    private void showProgressDlg(String title, String msg) {
        final ProgressDialog loadingDlg = new ProgressDialog(this);
        loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDlg.setTitle(title);
        loadingDlg.setIcon(android.R.drawable.ic_dialog_info);
        loadingDlg.setMessage(msg);
        loadingDlg.setCancelable(true);
        loadingDlg.show();
        new Thread() {
            public void run() {
                try {
                    progressRun();
                }
                catch (Exception e) {
                    loadingDlg.dismiss();
                }
                loadingDlg.dismiss();
            }
        }.start();
        loadingDlg
            .setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    doWork();
                }

            });
    }

    private void progressRun() {
        result = ConfigUtilHelper.request(url);
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "result---->" + result);
        }
        if (result == null) {
            return;
        }
        try {
            JSONObject joson = new JSONObject(result);
            int status = joson.getInt("status");
            resultMsg = joson.getString("message");
            if (ConfigUtilHelper.debug) {
                Log.i(TAG, "--resultMsg-->" + resultMsg);
            }
            if (status == 0) {
                isChanged = true;
            }
            else {
                isChanged = false;
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void checkInternet() {
        showSingleAlertDlg(getString(R.string.dialog_warning),
            getString(R.string.dialog_check_internet),
            getString(R.string.dialog_close));
    }

    private void doWork() {
        if (result == null) {
            if (!connectedNetwork()) {
                checkInternet();
            }
            return;
        }
        if (isChanged) {
            long dateMillis = System.currentTimeMillis();
            String loginDate = Long.toString(dateMillis);
            mDatabaseAdapter.open_user();
            Cursor c = mDatabaseAdapter.fetchAllUserData();
            if (c != null) {
                if (ConfigUtilHelper.debug) {
                    Log.i(TAG, "--user count----->" + c.getCount());
                }
                if (c.getCount() > 0) {
                    mDatabaseAdapter.deleteAllUserData();
                    mDatabaseAdapter.insertUserData(name, mobile, birth, sex,
                        card, scard, loginDate);

                }
                else {
                    mDatabaseAdapter.insertUserData(name, mobile, birth, sex,
                        card, scard, loginDate);
                }
            }
            SharedPreferences mSharedPreferences = getSharedPreferences(
                ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
            Editor edit = mSharedPreferences.edit();
            edit.putBoolean(ConfigUtilHelper.IS_LOGIN, true);
            edit.commit();

            mDatabaseAdapter.close_user();
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            finish();
        }
        else {
            if (resultMsg == null) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.change_info_err),
                    getString(R.string.dialog_yes));
            }
            else {
                showSingleAlertDlg(getString(R.string.notice), resultMsg,
                    getString(R.string.dialog_yes));
            }
        }
    }

    /**
     * 更新显示
     */
    private void updateDisplay() {
        birthT.setText(new StringBuilder().append(mYear).append("-")
            .append(mMonth + 1).append("-").append(mDay));
    }

    /**
     * 更新显示
     */
    private void updateDisplay_() {
        String mm = mMonth + "";
        if (mMonth < 10) {
            mm = "0" + mMonth;
        }
        String dd = mDay + "";
        if (mDay < 10) {
            dd = "0" + mDay;
        }
        birthT.setText(new StringBuilder().append(mYear).append("-").append(mm)
            .append("-").append(dd));
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear + 1;
        mDay = dayOfMonth;
        updateDisplay_();
    }
}